//
//  AppDelegate.m
//  ITrip
//
//  Created by dlios on 15-5-21.
//  Copyright (c) 2015年 lanou3g.com 蓝鸥科技. All rights reserved.
//

#import "AppDelegate.h"
#import "TravelNotesViewController.h"
#import "SubjectViewController.h"
#import "StrategyViewController.h"
#import "MineViewController.h"
#import "UMSocial.h"
#import <CoreLocation/CoreLocation.h>
#import "Database.h"
#import "GuideViewController.h"
#import <SDImageCache.h>
#import <UIImageView+AFNetworking.h>
#import <UMFeedback.h>
#define USERDEFAULT [NSUserDefaults standardUserDefaults]




@interface AppDelegate ()<CLLocationManagerDelegate, show>

@property(nonatomic, retain) CLLocationManager *locationManager;
@property (nonatomic, assign) NSInteger netNum;


@end

@implementation AppDelegate

- (void)dealloc
{
    [_window release];
    [super dealloc];
}


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    // Override point for customization after application launch.


//    NSLog(@"%@", NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject);

    


//    sleep(2);


    
    sleep(1);



    //UIStatusBarStyle
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    [_window release];
    
    [[NSUserDefaults standardUserDefaults] setObject:@"close" forKey:@"night"];
    if (![[NSUserDefaults standardUserDefaults] boolForKey:@"firstStart"]) {
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"firstStart"];
        GuideViewController *guide = [[GuideViewController alloc]init];
        self.window.rootViewController = guide;
        guide.delegate = self;
//        NSLog(@"第一次启动");
        [USERDEFAULT setObject:@"0" forKey:@"photoCount"];
    } else {
//        NSLog(@"不是第一次启动");
        [self createMyView];
    }
    
    
    
    return YES;
}

- (void)show
{
    [self createMyView];
}
    
- (void)createMyView
{
    // 友盟appkey
    [UMSocialData setAppKey:@"5569046f67e58e40e6002b92"];
    [UMFeedback setAppkey:@"5569046f67e58e40e6002b92"];
    
    
    [USERDEFAULT setObject:@"number" forKey:@"number"];
    [USERDEFAULT setObject:@"0.85" forKey:@"colorRed"];
    [USERDEFAULT setObject:@"0.85" forKey:@"colorYellow"];
    [USERDEFAULT setObject:@"0.85" forKey:@"colorBlue"];
    
    
    // 建立数据库
    [Database openDataBase];
    [Database createTable];
    
    // 第一次进入, 初始化应用
//    NSLog(@"%@", NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject);
    
    // 定位
    if ([CLLocationManager locationServicesEnabled]) {
        self.locationManager = [[CLLocationManager alloc] init];
        self.locationManager.delegate = self;
        self.locationManager.distanceFilter = 1000.0f;
        self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
//        NSLog(@"1");
    } else {
        NSLog(@"请开启定位功能");
    }
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)
    {
        [_locationManager requestWhenInUseAuthorization];  //调用了这句,就会弹出允许框了.
    }
    [_locationManager startUpdatingLocation];
    
   
    // 游记
    TravelNotesViewController *travelNotes = [[TravelNotesViewController alloc] init];
    UINavigationController *navTravelNotes = [[UINavigationController alloc] initWithRootViewController:travelNotes];
    UIImage *imageTravelNotes1 = [UIImage imageNamed:@"iconfont-bijiben"];
    UIImage *imageTravelNotes2 = [UIImage imageNamed:@"iconfont-bijiben_blue"];
    imageTravelNotes1 = [imageTravelNotes1 imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    imageTravelNotes2 = [imageTravelNotes2 imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    navTravelNotes.tabBarItem = [[UITabBarItem alloc] initWithTitle:@"游记" image:imageTravelNotes1 selectedImage:imageTravelNotes2];
    
    // 专题
    SubjectViewController *subject = [[SubjectViewController alloc] init];
    UINavigationController *navSubject = [[UINavigationController alloc] initWithRootViewController:subject];
    UIImage *imageSubject1 = [UIImage imageNamed:@"iconfont-zhuanti"];
    UIImage *imageSubject2 = [UIImage imageNamed:@"iconfont-zhuanti_blue"];
    imageSubject1 = [imageSubject1 imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    imageSubject2 = [imageSubject2 imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    navSubject.tabBarItem = [[UITabBarItem alloc] initWithTitle:@"专题" image:imageSubject1 selectedImage:imageSubject2];
    
    
    // 攻略
    StrategyViewController *strategy = [[StrategyViewController alloc] init];
    UINavigationController *navStrategy = [[UINavigationController alloc] initWithRootViewController:strategy];
    UIImage *imageStrategy1 = [UIImage imageNamed:@"iconfont-gonglve"];
    UIImage *imageStrategy2 = [UIImage imageNamed:@"iconfont-gonglve_blue"];
    imageStrategy1 = [imageStrategy1 imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    imageStrategy2 = [imageStrategy2 imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    navStrategy.tabBarItem = [[UITabBarItem alloc] initWithTitle:@"攻略" image:imageStrategy1 selectedImage:imageStrategy2];
    
    
    // 我的
    MineViewController *mine = [[MineViewController alloc] init];
    UINavigationController *navMine = [[UINavigationController alloc] initWithRootViewController:mine];
    UIImage *imageMine1 = [UIImage imageNamed:@"iconfont-wode"];
    UIImage *imageMine2 = [UIImage imageNamed:@"iconfont-wode_blue"];
    imageMine1 = [imageMine1 imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    imageMine2 = [imageMine2 imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    navMine.tabBarItem = [[UITabBarItem alloc] initWithTitle:@"我的" image:imageMine1 selectedImage:imageMine2];
    
    // tabBar
    UITabBarController *tabBarController = [[UITabBarController alloc] init];
    tabBarController.tabBar.translucent = NO;
    tabBarController.tabBar.barTintColor = [UIColor colorWithRed:255/255.0 green:255/255.0 blue:255/255.0 alpha:1];
//    NSLog(@"%f", [[USERDEFAULT objectForKey:@"colorRed"] floatValue]);
    tabBarController.viewControllers = [NSArray arrayWithObjects:navTravelNotes, navSubject, navStrategy, navMine, nil];
    // 导航栏属性设置
    
    [[UINavigationBar appearance] setBarTintColor:[UIColor colorWithRed:64/255.0 green:188/255.0 blue:233/255.0 alpha:1]];
    [[UINavigationBar appearance] setTranslucent:NO];
    self.window.rootViewController = tabBarController;
    
    
    
    
    [travelNotes release];
    [strategy release];
    [subject release];
    [mine release];
    [navMine release];
    [navStrategy release];
    [navSubject release];
    [navTravelNotes release];
    [tabBarController release];
    
   
    
}

//  ios 5 之前
//- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
//{
//    NSString *lat = [NSString stringWithFormat:@"%f", newLocation.coordinate.latitude];
//    [USERDEFAULT setObject:lat forKey:@"lat"];
//    NSString *lng = [NSString stringWithFormat:@"%f", newLocation.coordinate.longitude];
//    [USERDEFAULT setObject:lng forKey:@"lng"];
//    [manager stopUpdatingLocation];
//}

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
    //此处locations存储了持续更新的位置坐标值，取最后一个值为最新位置，如果不想让其持续更新位置，则在此方法中获取到一个值之后让locationManager stopUpdatingLocation
    CLLocation *currentLocation = [locations lastObject];
    CLLocationCoordinate2D coor = currentLocation.coordinate;
    // 获取国家, 城市等信息 (其他属性点进去看)
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    [geocoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray *placemarks, NSError *error) {
        if (placemarks.count > 0) {
            CLPlacemark *placemark = [placemarks objectAtIndex:0];
            NSArray *addressArray = [placemark.addressDictionary objectForKey:@"FormattedAddressLines"];
            NSMutableString *addR = [[NSMutableString alloc] init];
            for (int i = 0; i < addressArray.count; i++) {
                [addR appendString:addressArray[i]];
            }
//            NSLog(@"&******%@", addressArray);
            NSString *lat = [NSString stringWithFormat:@"%f", coor.latitude];
            NSString *lng = [NSString stringWithFormat:@"%f", coor.longitude];
            [USERDEFAULT setObject:lat forKey:@"lat"];
            [USERDEFAULT setObject:lng forKey:@"lng"];
        }
    }];
    [_locationManager stopUpdatingLocation];
}


// 定位失误
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
    if (error.code == kCLErrorDenied) {
        NSLog(@"wrong");
    }
}










- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

@end
